package com.colin.jipay.pinduoduo_hook;

import android.os.Bundle;

import com.colin.jipay.utils.JsonUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * @author lemlin
 * @date 2019/7/23
 * <p>
 * 拼多多商家版
 */
public class PDDSellerHook {

    private XC_LoadPackage.LoadPackageParam lpparam;

    public PDDSellerHook(XC_LoadPackage.LoadPackageParam lpparam) {
        this.lpparam = lpparam;
    }

    /**
     * Hook 拼多多商家订单信息
     */
    public void hookPddOrderInfo() {

        //HOOK 商品主页的接收器方法，该方法会接收到各种的推送通知信息，以下判断如果为系统消息（systemMessageChanged）则做获取订单列表操作
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.merchant.data.ui.ShopFragment", lpparam.classLoader),
                "onReceive", XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.framework.b.a", lpparam.classLoader), new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        String json = JsonUtils.objectToString(param.args[0]);
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.optString("a").equals("systemMessageChanged")) {
                            XposedBridge.log("HOOK com.xunmeng.merchant.data.ui.ShopFragment类的onReceive方法");

                            callMethodUnshippedOrder(lpparam);
                        }
                    }
                });

        //HOOK 商品主页，在onCreate中另起线程，（死循环）每隔3秒主动发起获取订单列表信息
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.merchant.data.ui.ShopFragment", lpparam.classLoader),
                "onCreate", Bundle.class, new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        XposedBridge.log("HOOK com.xunmeng.merchant.data.ui.ShopFragment类的onCreate方法");

                        //原因：有时拼多多并不能接收到推送信息，故另起线程主动发起请求
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (true) {

                                    callMethodUnshippedOrder(lpparam);
                                    try {
                                        Thread.sleep(3000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                    }
                });

        //HOOK 在拼多多当中此方法是（待发货订单）网络请求
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.merchant.order.c.u", lpparam.classLoader),
                "a", int.class, int.class, long.class, long.class, new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        XposedBridge.log("入参【HOOK 待发货网络请求参数信息】" + param.args[0] + "," + param.args[1] + "," + param.args[2] + "," + param.args[3]);
                    }
                });

        //HOOK 发起网络请求返回的必经之路，在此拦截订单信息
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.merchant.network.rpc.framework.c", lpparam.classLoader),
                "onDataReceived", Object.class, new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);

                        String className = param.args[0].getClass().getName();
                        if (className.equals("com.xunmeng.merchant.network.protocol.order.QueryOrderListResp")) {

                            //解析打印待发货订单列表集合，如有需要解析出第一条数据便是最新订单
                            //例：[{"avatar":"http:\/\/pinduoduoimg.yangkeduo.com\/avatar\/default\/2.png","bizType":0,"buyerMemo":"","cityId":53,"cityName":"福州市",
                            // "confirmTime":1562235790,"createdAt":1562235783,"discountAmount":0,"districtId":520,"districtName":"仓山区","eventDiscount":0,"eventType":0,
                            // "favoriteStatus":false,"goodsAmount":800,"goodsId":20754312003,"goodsName":"运动拖鞋夏季新款女式休闲散步凉拖卡通可爱风少女心萌萌哒凉鞋",
                            // "goodsNumber":1,"goodsPrice":800,"groupOrderId":"810425870951671625","groupStatus":1,"groupTime":1562235790,"isExistFineInfo":0,
                            // "luckyStatus":0,"mallId":219026440,"merchantDiscount":0,"nickname":"1*********5","orderAmount":800,"orderId":"810425870951671625",
                            // "orderSn":"190704-425870951671625","orderStatus":1,"orderTime":1562235783,"outGoodsSn":"","outSkuSn":"","payStatus":2,"payTime":1562235790,
                            // "platformDiscount":0,"promiseShippingTime":1562408590,"provinceId":4,"provinceName":"福建省","receiveName":"林荔敏","remarkStatus":0,
                            // "riskStatus":0,"sendSingleGroupCard":0,"shippingAddress":"金港路金山桔园和园28栋1梯502","shippingAmount":0,"shippingId":0,"shippingStatus":0,
                            // "shippingTime":0,"skuId":293524699952,"spec":"黄色","thumbUrl":"http:\/\/t00img.yangkeduo.com\/goods\/images\/2019-07-01\/9a4ec923bb9d5b7063bdc74aea6fbfab.jpeg",
                            // "totalDiscount":0,"tradeType":0,"type":0,"uid":0,"useSingleGroupCard":false}]
                            String jsonStr = JsonUtils.objectToString(param.args[0]);
                            JSONObject jsonResult = new JSONObject(jsonStr);
                            JSONArray jsonPageItems = new JSONObject(jsonResult.optString("result")).getJSONArray("pageItems");
                            if (jsonPageItems.length() == 0) {
                                return;
                            }
                            XposedBridge.log("总的有" + jsonPageItems.length() + "个订单，第一条数据为：" + jsonPageItems.get(0).toString());
                        }
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                    }
                });
    }

    /**
     * 调起对应的网络请求（待发货）订单列表的方法
     */
    private void callMethodUnshippedOrder(XC_LoadPackage.LoadPackageParam lpparam) {

        //实例化对应类，并调起对应的网络请求方法（该方法是获取网络待发货的订单列表）
        String className = "com.xunmeng.merchant.order.c.u";
        Class<?> aClass = XposedHelpers.findClassIfExists(className, lpparam.classLoader);
        Object object = XposedHelpers.newInstance(aClass);
        int i1 = 1, i2 = 10;
        Long longValue = System.currentTimeMillis();
        long l1 = (longValue - 2592000000L) / 1000, l2 = longValue / 1000;
        XposedHelpers.callMethod(object, "a", i1, i2, l1, l2);
    }
}
